<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-alert title="注意: 只允许为第三级分类设置相关参数"
                type="warning"
                show-icon
                :closable="false">
      </el-alert>
      <!-- 级联选择框 -->
      <el-row class="cascader">
        <el-col>
          <span>选择商品分类 : </span>
          <el-cascader v-model="value"
                       :options="paramsList"
                       :props="propConfig"
                       @change="handleChange">
          </el-cascader>
        </el-col>
      </el-row>
      <!-- 标签页 -->
      <el-tabs v-model="activeName"
               @tab-click="handleClick">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数"
                     name="many">
          <el-button type="primary"
                     @click="setParams">
            添加参数
          </el-button>
          <!-- table栏 -->
          <el-table :data="manyTabelData"
                    style="width: 100%"
                    border>
            <el-table-column type="expand"
                             width="50">
              <template slot-scope="scope">

                <el-tag v-for="(item,i) in scope.row.attr_vals"
                        :key="i"
                        closable
                        @close="inpHandleColse(i,scope.row)">
                  {{item}}
                </el-tag>
                <el-input class="input-new-tag"
                          v-if="scope.row.inputVisible"
                          v-model="scope.row.inputValue"
                          ref="saveTagInput"
                          size="small"
                          @keyup.enter.native="handleInputConfirm(scope.row)"
                          @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else
                           class="button-new-tag"
                           size="small"
                           @click="showInput(scope.row)">+ New Tag</el-button>

              </template>
            </el-table-column>
            <el-table-column type="index"
                             width="50">
            </el-table-column>
            <el-table-column prop="attr_name"
                             label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary"
                           icon="el-icon-edit"
                           size="mini"
                           @click="editparamsBtn(scope.row)">编辑</el-button>
                <el-button type="danger"
                           icon="el-icon-delete"
                           size="mini"
                           @click="delParams(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

        </el-tab-pane>
        <!-- 静态参数 -->
        <el-tab-pane label="
                           静态参数"
                     name="only">
          <el-button type="primary"
                     @click="setParams">
            添加属性
          </el-button>
          <!-- table栏 -->
          <el-table :data="onlyTableData"
                    style="width: 100%"
                    border>
            <el-table-column type="expand"
                             width="50">
              <template slot-scope="scope">

                <el-tag v-for="(item,i) in scope.row.attr_vals"
                        :key="i"
                        closable
                        @close="inpHandleColse(i,scope.row)">
                  {{item}}
                </el-tag>
                <el-input class="input-new-tag"
                          v-if="scope.row.inputVisible"
                          v-model="scope.row.inputValue"
                          ref="saveTagInput"
                          size="small"
                          @keyup.enter.native="handleInputConfirm(scope.row)"
                          @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else
                           class="button-new-tag"
                           size="small"
                           @click="showInput(scope.row)">+ New Tag</el-button>

              </template>
            </el-table-column>
            <el-table-column type="index"
                             width="50">
            </el-table-column>
            <el-table-column prop="attr_name"
                             label="属性名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary"
                           icon="el-icon-edit"
                           size="mini"
                           @click="editparamsBtn(scope.row)">编辑</el-button>
                <el-button type="danger"
                           icon="el-icon-delete"
                           size="mini"
                           @click="delParams(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数/属性对话框 -->
    <el-dialog :title="'添加'+titleText"
               :visible.sync="addDialogVisible"
               width="50%"
               @close="addParamsClose">
      <el-form :model="paramsForm"
               :rules="paramsRule"
               ref="paramsRef"
               label-width="100px">
        <el-form-item :label="titleText"
                      prop="name">
          <el-input v-model="paramsForm.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑属性对话框 -->
    <el-dialog :title="'编辑'+titleText"
               :visible.sync="editDialogVisible"
               width="50%"
               @close="editParamsClose">
      <el-form :model="itemData"
               :rules="paramsRule"
               ref="editParamsRef"
               label-width="100px">
        <el-form-item :label="titleText"
                      prop="attr_name">
          <el-input v-model="itemData.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer"
            class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>

export default {
  data () {
    return {
      // 获取的商品分类表单
      paramsList: [],
      // 选中的分类
      value: [],
      // 级联选择框的配置项
      propConfig: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 标签页当前选中
      activeName: 'many',
      // 获取到的静态信息
      onlyTableData: [],
      // 获取到的动态信息
      manyTabelData: [],
      // 对话框的显示与隐藏
      addDialogVisible: false,
      // 表单的数据对象
      paramsForm: {},
      // 表单的验证规则
      paramsRule: {
        name: [
          { required: true, message: '请输入参数', trigger: 'blur' },
          { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' }
        ],
        attr_name: [
          { required: true, message: '请输入参数', trigger: 'blur' },
          { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' }
        ]
      },
      // 控制编辑对话框显示隐藏
      editDialogVisible: false,
      // 当前选中编辑的数据
      itemData: {}

    }
  },
  methods: {
    // 获取商品分类表单
    async getParamsList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取列表失败')
      this.paramsList = res.data
    },
    // 监听商品分类的值
    handleChange () {
      // 判断选择的是不是三级分类, 不是则清空
      if (this.value.length !== 3) {
        this.value = []
        this.onlyTableData = []
        this.manyTabelData = []
        return null
      }
      // 当选中时查询对应参数
      this.reqParams()
    },
    // 获取查询的参数
    async reqParams () {
      const { data: res } = await this.$http.get(`categories/${this.reqID}/attributes/`, {
        params: {
          sel: this.activeName
        }
      })
      // if (res.meta.status !== 200) return this.$message.error('获取列表失败')
      // this.$message.success('获取列表成功')
      // console.log(res)
      if (this.activeName === 'many') {
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          item.inputVisible = false
          item.inputValue = ''
        })

        this.manyTabelData = res.data
      } else {
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          item.inputVisible = false
          item.inputValue = ''
        })
        this.onlyTableData = res.data
      }
    },
    // 监听标签页变动
    handleClick () {
      if (this.value.length === 3) {
        return this.reqParams()
      }
    },
    // 添加对话框的点击按钮
    setParams () {
      this.addDialogVisible = true
    },
    // 确任添加参数/属性
    addParams () {
      this.$refs.paramsRef.validate(async valid => {
        if (!valid) return this.$message.error('提交失败')
        const { data: res } = await this.$http.post(`categories/${this.reqID}/attributes`, {
          attr_name: this.paramsForm.name,
          attr_sel: [this.activeName]
        })
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.$message.success('添加成功')
        this.reqParams()
        this.addDialogVisible = false
      })
    },
    // 点击编辑按钮触发
    editparamsBtn (data) {
      this.itemData = data

      this.editDialogVisible = true
    },
    // 监听添加对话框的关闭
    addParamsClose () {
      this.$refs.paramsRef.resetFields()
    },
    // 监听编辑对话框的关闭
    editParamsClose () {
      this.$refs.editParamsRef.resetFields()
    },
    // 确任编辑
    editParams () {
      this.$refs.editParamsRef.validate(async valid => {
        if (!valid) return null
        const { data: res } = await this.$http.put(`categories/${this.itemData.cat_id}/attributes/${this.itemData.attr_id}`, {
          attr_name: this.itemData.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$message.error('编辑失败')
        this.$message.success('编辑成功')
        this.reqParams()
        this.editDialogVisible = false
      })
    },
    // 删除指定参数
    async delParams (row) {
      const confirm = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirm === 'cancel') {
        this.$message.info('已取消操作')
        return null
      }
      const { data: res } = await this.$http.delete(`categories/${row.cat_id}/attributes/${row.attr_id}`)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      this.reqParams()
    },
    // 点击添加tag按钮
    showInput (row) {
      console.log(row)

      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 添加tag的处理事件
    async handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return null
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputVisible = false
      row.inputValue = ''
      this.saveAttrvals(row)
    },
    async saveAttrvals (row) {
      const { data: res } = await this.$http.put(`categories/${this.reqID}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('编辑失败')
      this.$message.success('编辑成功')
    },
    // tag标签的删除事件
    inpHandleColse (i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrvals(row)
    }
  },
  created () {
    this.getParamsList()
  },
  computed: {
    reqID: function () {
      if (this.value.length === 3) {
        return this.value[this.value.length - 1]
      }
      return null
    },
    titleText: function () {
      if (this.activeName === 'only') {
        return '静态参数'
      }
      return '动态参数'
    }
  }
}
</script>
<style lang="less" scoped>
.cascader {
  margin: 20px 0;
  .el-cascader {
    margin-left: 15px;
  }
}
.el-table {
  margin-top: 15px;
}
.el-tag {
  margin: 0 10px;
}
.input-new-tag {
  width: 100px;
}
</style>
